"""
调试输出测试脚本

功能：
- 测试各个控制器的对外接口调试输出是否正常工作
- 验证调试信息的格式和内容是否符合预期
- 确保多服务调试时能够正确显示接口调用、主要数据和数据流进度

使用方法：
1. 启动FastAPI服务器
2. 运行此测试脚本
3. 观察控制台输出的调试信息

原理：
通过HTTP请求模拟客户端调用各个对外接口，观察服务器端的调试输出
"""

import requests
import json
import time
from datetime import datetime
from typing import Dict, Any

# 测试配置
BASE_URL = "http://localhost:8000"
TEST_SESSION_ID = "test_session_123"
TEST_ROOM_ID = "test_room_456"

class DebugOutputTester:
    """调试输出测试器"""
    
    def __init__(self, base_url: str):
        self.base_url = base_url
    
    def test_tablet_brainwave_upload(self) -> bool:
        """测试平板脑波数据上传接口的调试输出"""
        print("\n=== 测试平板脑波数据上传接口 ===")
        
        # 构造测试数据 - 符合TabletBrainWaveRequest模型
        test_data = {
            "session_id": TEST_SESSION_ID,
            "room_id": TEST_ROOM_ID,
            "timestamp": int(datetime.now().timestamp() * 1000),
            # 原始EEG数据 - 512Hz采样率，每秒512个数据点
            "raw_value": [100 + i for i in range(512)],  # 生成512个测试数据点
            # 8个频段功率数据
            "delta": 150,
            "theta": 120,
            "low_alpha": 180,
            "high_alpha": 200,
            "low_beta": 160,
            "high_beta": 140,
            "low_gamma": 80,
            "mid_gamma": 60,
            # NeuroSky算法输出
            "attention": 75,
            "meditation": 68,
            # 信号质量指标
            "poor_signal": 25,
            "blink_strength": 12
        }
        
        try:
            response = requests.post(
                f"{self.base_url}/api/v1/tablet/brainwave",
                json=test_data,
                headers={"Content-Type": "application/json"},
                timeout=10
            )
            if response.status_code == 200:
                result = response.json()
                print(f"✓ 接口调用成功，响应: {result}")
                return True
            else:
                print(f"✗ 接口调用失败，状态码: {response.status_code}")
                return False
        except Exception as e:
            print(f"✗ 接口调用异常: {str(e)}")
            return False
    
    def test_tablet_realtime_analysis(self) -> bool:
        """测试平板实时分析接口的调试输出"""
        print("\n=== 测试平板实时分析接口 ===")
        
        try:
            response = requests.get(
                f"{self.base_url}/api/v1/tablet/realtime/{TEST_SESSION_ID}",
                timeout=10
            )
            if response.status_code in [200, 404]:  # 404也是正常的，因为可能没有数据
                result = response.json()
                print(f"✓ 接口调用成功，响应: {result}")
                return True
            else:
                print(f"✗ 接口调用失败，状态码: {response.status_code}")
                return False
        except Exception as e:
            print(f"✗ 接口调用异常: {str(e)}")
            return False
    
    def test_tablet_analysis_latest(self) -> bool:
        """测试平板深度分析接口的调试输出"""
        print("\n=== 测试平板深度分析接口 ===")
        
        try:
            response = requests.get(
                f"{self.base_url}/api/v1/tablet/analysis/{TEST_SESSION_ID}/latest",
                timeout=10
            )
            if response.status_code in [200, 404]:  # 404也是正常的，因为可能没有数据
                result = response.json()
                print(f"✓ 接口调用成功，响应: {result}")
                return True
            else:
                print(f"✗ 接口调用失败，状态码: {response.status_code}")
                return False
        except Exception as e:
            print(f"✗ 接口调用异常: {str(e)}")
            return False
    
    def test_cloud_storage_upload_raw(self) -> bool:
        """测试云存储原始数据上传接口的调试输出"""
        print("\n=== 测试云存储原始数据上传接口 ===")
        
        # 构造测试数据
        test_data = {
            "session_id": TEST_SESSION_ID,
            "room_id": TEST_ROOM_ID,
            "timestamp": int(datetime.now().timestamp() * 1000),
            "data_type": "raw_brainwave",
            "file_size": 1024,
            "checksum": "test_checksum_123"
        }
        
        try:
            response = requests.post(
                f"{self.base_url}/api/v1/cloud-storage/upload-raw-data",
                json=test_data,
                headers={"Content-Type": "application/json"},
                timeout=10
            )
            if response.status_code == 200:
                result = response.json()
                print(f"✓ 接口调用成功，响应: {result}")
                return True
            else:
                print(f"✗ 接口调用失败，状态码: {response.status_code}")
                return False
        except Exception as e:
            print(f"✗ 接口调用异常: {str(e)}")
            return False
    
    def test_cloud_storage_status(self) -> bool:
        """测试云存储状态接口的调试输出"""
        print("\n=== 测试云存储状态接口 ===")
        
        try:
            response = requests.get(
                f"{self.base_url}/api/v1/cloud-storage/status",
                timeout=10
            )
            if response.status_code == 200:
                result = response.json()
                print(f"✓ 接口调用成功，响应: {result}")
                return True
            else:
                print(f"✗ 接口调用失败，状态码: {response.status_code}")
                return False
        except Exception as e:
            print(f"✗ 接口调用异常: {str(e)}")
            return False
    
    def test_filtered_data_upload(self) -> bool:
        """测试过滤数据上传接口的调试输出"""
        print("\n=== 测试过滤数据上传接口 ===")
        
        # 构造测试数据
        test_data = {
            "brain_wave_data": {
                "session_id": TEST_SESSION_ID,
                "room_id": TEST_ROOM_ID,
                "timestamp": int(datetime.now().timestamp() * 1000),
                "time_series": {
                    "data": [1.1, 2.2, 3.3, 4.4, 5.5],
                    "timestamps": [110, 220, 330, 440, 550],
                    "sampling_rate": 250.0
                },
                "processing_stage": "filtered"
            }
        }
        
        try:
            response = requests.post(
                f"{self.base_url}/api/v1/filtered-data/upload-filtered-data",
                json=test_data,
                headers={"Content-Type": "application/json"},
                timeout=10
            )
            if response.status_code == 200:
                result = response.json()
                print(f"✓ 接口调用成功，响应: {result}")
                return True
            else:
                print(f"✗ 接口调用失败，状态码: {response.status_code}")
                return False
        except Exception as e:
            print(f"✗ 接口调用异常: {str(e)}")
            return False
    
    def test_filtered_data_status(self) -> bool:
        """测试过滤数据状态接口的调试输出"""
        print("\n=== 测试过滤数据状态接口 ===")
        
        try:
            response = requests.get(
                f"{self.base_url}/api/v1/filtered-data/status",
                timeout=10
            )
            if response.status_code == 200:
                result = response.json()
                print(f"✓ 接口调用成功，响应: {result}")
                return True
            else:
                print(f"✗ 接口调用失败，状态码: {response.status_code}")
                return False
        except Exception as e:
            print(f"✗ 接口调用异常: {str(e)}")
            return False
    
    def run_all_tests(self) -> Dict[str, bool]:
        """运行所有测试"""
        print("开始测试所有对外接口的调试输出...")
        print("注意：请确保FastAPI服务器已启动在 http://localhost:8000")
        print("=" * 60)
        
        # 等待用户确认
        input("按回车键开始测试...")
        
        results = {}
        
        # 测试平板控制器接口
        results["tablet_brainwave_upload"] = self.test_tablet_brainwave_upload()
        time.sleep(1)  # 间隔1秒
        
        results["tablet_realtime_analysis"] = self.test_tablet_realtime_analysis()
        time.sleep(1)
        
        results["tablet_analysis_latest"] = self.test_tablet_analysis_latest()
        time.sleep(1)
        
        # 测试云存储控制器接口
        results["cloud_storage_upload_raw"] = self.test_cloud_storage_upload_raw()
        time.sleep(1)
        
        results["cloud_storage_status"] = self.test_cloud_storage_status()
        time.sleep(1)
        
        # 测试过滤数据控制器接口
        results["filtered_data_upload"] = self.test_filtered_data_upload()
        time.sleep(1)
        
        results["filtered_data_status"] = self.test_filtered_data_status()
        
        return results
    
    def print_test_summary(self, results: Dict[str, bool]):
        """打印测试总结"""
        print("\n" + "=" * 60)
        print("测试总结:")
        print("=" * 60)
        
        success_count = sum(1 for success in results.values() if success)
        total_count = len(results)
        
        for test_name, success in results.items():
            status = "✓ 成功" if success else "✗ 失败"
            print(f"{test_name}: {status}")
        
        print(f"\n总计: {success_count}/{total_count} 个测试通过")
        
        if success_count == total_count:
            print("🎉 所有调试输出测试都通过了！")
        else:
            print("⚠️  部分测试失败，请检查服务器状态和调试输出")

def main():
    """主函数"""
    tester = DebugOutputTester(BASE_URL)
    results = tester.run_all_tests()
    tester.print_test_summary(results)

if __name__ == "__main__":
    main()